package com.wchen.project.zk.demo;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2020-01-16 23:38
 */

public class ZookeeperConnectSimple implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws IOException {
        ZooKeeper zookeeper = new ZooKeeper("home:2181",5000, new ZookeeperConnectSimple());
        System.out.println("zookeeper connect stat : " + zookeeper.getState());
        try {
            connectedSemaphore.await();
            System.out.println("success!");
        } catch (InterruptedException e) {
            System.out.println("ZooKeeper session established");
        }
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("Receive watched event:" + watchedEvent);
        if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
            connectedSemaphore.countDown();
        }
    }
}
